
const sns = require('./service/sns/sns');//app.js
App({
  onLaunch: function () {
    let jwt = wx.getStorageSync('jwt')
    let userinfo = wx.getStorageSync('userinfo')
    let openId = userinfo.openid;

    // console.log(userinfo);


    if (jwt && userinfo) { // 如果有token且没有过期
      this.globalData.jwt = jwt
      this.globalData.userInfo = {
        openid: openId,
        nickName: userinfo.nickName,
        avatarUrl: userinfo.avatarUrl
      }
      // console.log(this.globalData.userInfo);
      console.log('globalData 赋值成功')
      //如果子页面中定义了该函数，则调用
      if (this.userInfoReadyCallback) {
        this.userInfoReadyCallback()
      }
    } else {
    // 登录
      wx.login({
        success: res => {
          // console.log(res);
          let code = res.code
          wx.getSetting({
            success: res => {
              // console.log(res);
              if (!res.authSetting['scope.userInfo']) {
                wx.authorize({ // 向用户发起授权请求
                  scope: 'scope.userInfo',
                  success: (res) => { // 用户同意授权
                    wx.reportAnalytics('agree_auth', {})
                    this.login(code)
                  },
                  fail: () => { // 用户拒绝授权
                    wx.reportAnalytics('deny_auth', {})
                    this.introduceAuth()
                  }
                })

                
              }
              else { //如果用户已经授权
              this.login(code) //通过code进行登录
            }
            }
          })
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
        }
      })
    }
  },
  // 进入login的必要条件：1、本地没有token或token已过期; 2、用户必定已授权 scope.userInfo
  login: function (code) {
    console.log('enter login...')
    wx.showLoading({
      title: '正在登录',
      mask: true
    })
    let _this = this;
    wx.getUserInfo({
      // withCredentials: unionid != '' ? false : true,
      success: (res) => {
        // console.log(res)
        const userInfo = res.userInfo;
        let nickname = userInfo.nickName;
        let head_img = userInfo.avatarUrl;
        sns.getToken(code, nickname, head_img).then(res => {
          if (res.data.code === 1000) {
            const openid = res.data.data.openid, jwt = res.data.data.token;
            wx.hideLoading();
            //设置globalData和localStorage
            this.globalData.jwt = jwt;
            this.globalData.userInfo = {
              openid: openid,
              nickName: userInfo.nickName,
              avatarUrl: userInfo.avatarUrl
            }
            // console.log(this.globalData);
            wx.setStorageSync('jwt', _this.globalData.jwt)
            wx.setStorageSync('userinfo', _this.globalData.userInfo)
            if (this.userInfoReadyCallback) {
              this.userInfoReadyCallback()
            }
          } else {
            console.log(res.data.msg)
          }
        }).catch(res => {
          console.log(res.errMsg)
        })
        

      },
      fail: function (res) {
        console.log(res);
      }
    })
    
  },

  introduceAuth: function () {
    wx.showModal({
      title: '温馨提示',
      content: '只有同意授权美篇小程序才能发现更多精彩，美篇不会将您的信息提供给第三方，请同意设置或删除小程序重新进入。',
      confirmColor: '#2F92FF',
      showCancel: false,
      success: (res) => { // 用户点击“确定”
        wx.openSetting({ // 跳转到“设置”界面
          success: (res) => {
            console.log(res)
            if (res.authSetting['scope.userInfo']) { // 如果开启了授权
              wx.login({
                success: res => {
                  wx.reportAnalytics('agree_auth_retry', {})
                  let code = res.code
                  this.login(code)
                }
              })
            } else { // 如果用户依然没有开启授权，一直安利
              this.introduceAuth()
            }
          }
        })
      }
    })
  },
  globalData: {
    userInfo: null
  }
})